package cn.xwlin.task;

import cn.xwlin.consts.Result;
import cn.xwlin.entity.TicketInProgressInfo;
import cn.xwlin.mapper.TicketInProgressInfoMapper;
import cn.xwlin.service.CreateMatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class CreateMatchOrderTask02 {

    @Autowired
    private CreateMatchService createMatchService;
    @Autowired
    private TicketInProgressInfoMapper ticketInProgressInfoMapper;

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Scheduled(cron = "0/2 * * * * ?")
    public void createMatchOrder() {
        System.out.println("Task 0/2 Processing");
        int count = 0;
        List<TicketInProgressInfo> ticketInProgressInfos = ticketInProgressInfoMapper.listToDeal(2, 0, 10);
        if (CollectionUtils.isEmpty(ticketInProgressInfos)) {
            System.out.println("Task 0/2 Processing End, count= " + count);
            return;
        }

        for (TicketInProgressInfo ticketInProgressInfo : ticketInProgressInfos) {
            if (!StringUtils.hasLength(ticketInProgressInfo.getRegionInfo())) {
                continue;
            }
            String[] split = ticketInProgressInfo.getRegionInfo().split(",");
            for (String regionUuid : split) {
                count++;
                executorService.submit(() -> {
                    Result match = createMatchService.createMatch(ticketInProgressInfo.getId(), Long.valueOf(regionUuid));
                    if (match.isSuccess()) {
                        System.out.println("###成功啦###成功啦###");
                    }
                });
            }
        }
        System.out.println("Task 0/2 Processing End, count= " + count);
    }
}
